﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Synchros
{
    public partial class FrmConfig : Form
    {
        public FrmConfig()
        {
            InitializeComponent();
        }
        
        public FrmConfig(bool isSyncStart)
        {
            this.isSyncStart = isSyncStart;
            InitializeComponent();
        }

        #region 全局变量

        // 同步是否在运行
        private bool isSyncStart;
        // 当前服务器配置
        private DataTable dtGlobalServer = new DataTable();

        // 当前数据库配置
        private DataTable dtGlobalDatabase = new DataTable();

        // 同步组配置List
        private List<SyncItem> lstSync = new List<SyncItem>();
        // 同步组配置Table
        private DataTable dtSyncGp = new DataTable();
        // 当前同步组的索引
        private int iSyncGpSelectedRowIndex;
        // 当前同步库的索引
        private int iSyncDbSelectedRowIndex;
        // 当前同步表的索引
        private int iSyncTbSelectedRowIndex;

        #endregion 全局变量

        #region 加载配置
        private void From_Load(object sender, EventArgs e)
        {
            //加载服务器配置
            XmlHelper.FillConnConfig(dtGlobalServer);//dtGlobalServer = XmlHelper.LoadConfig(SyncType.Server);
            //绑定配置到表单
            cbxServer.DataSource = dtGlobalServer;
            cbxServer.DisplayMember = "Server";
            cbxServer.ValueMember = "Server";
            cbxServer.Text = "";
            this.cbxServer.SelectedIndexChanged += new System.EventHandler(this.cbxServer_SelectedIndexChanged);

            // 填充并显示已配置的同步组列表
            XmlHelper.FillSyncConfig(lstSync);
            {
                dtSyncGp.Columns.Add("SgName",typeof(string));
                dtSyncGp.Columns.Add("Spaced", typeof(int));
                dtSyncGp.Columns.Add("IsSync", typeof(bool));
            }
            ListToTable(lstSync, dtSyncGp);
            dgvSyncGp.DataSource = dtSyncGp;
            if (lstSync.Count > 0)
            {
                SyncGpSelectedRow(0);
            }

            //绑带消息事件
            SqlHelper.UpdatePromptEvent += new SqlHelper.UpdatePromptDelegate(ConfigureMessageEvent);
        }
        #endregion

        #region 保存配置
        private void btnSyncSave_Click(object sender, EventArgs e)
        {
            groupBox1.Enabled = false;
            Thread th = new Thread(new ThreadStart(UpdatePromptWork));
            th.Start();
        }
        // 保存配置工作纯程
        private void UpdatePromptWork()
        {
            TableToList(dtSyncGp, lstSync);
            try
            {
                // 保存配置
                XmlHelper.SaveSyncConfig(lstSync);
                //// 加载配置
                //XmlHelper.FillSyncConfig(lstSync);
                // 配置数据库变更数据捕获
                SqlHelper.ConfigureChangedDataCatch(lstSync, true);//true
                //From_Load(null, null);//重新装载页面
                FromEnabledEvent(true);
                if (isSyncStart)
                {
                    MessageBox.Show("保存成功!该配置将在下一次启动同步时生效.");
                }
                else
                {
                    MessageBox.Show("保存成功!");
                }
            }
            catch (Exception ex)
            {
                FromEnabledEvent(true);
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region 配置事件

        // 绑定服务器对应的数据库
        private void cbxServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (iSyncGpSelectedRowIndex > -1 && iSyncGpSelectedRowIndex < lstSync.Count)
            {
                if (cbxServer.Text.Trim()!="" && cbxServer.SelectedIndex > -1)
                {
                    //绑定来源数据库
                    string strServer = dtGlobalServer.Rows[cbxServer.SelectedIndex]["Server"].ToString();
                    string strUserID = dtGlobalServer.Rows[cbxServer.SelectedIndex]["UserID"].ToString();
                    string strPassword = dtGlobalServer.Rows[cbxServer.SelectedIndex]["Password"].ToString();

                    try
                    {
                        dtGlobalDatabase = SqlHelper.GetDatabases(strServer, strUserID, strPassword);
                        //移除在(所有)配置中已经存在的同步库
                        for (int iGroup = 0; iGroup < lstSync.Count; iGroup++)
                        {
                            DataTable dtSyncDb = lstSync[iGroup].SyncDb;
                            for (int iDes = 0; iDes < dtSyncDb.Rows.Count; iDes++)
                            {
                                for (int iSrc = 0; iSrc < dtGlobalDatabase.Rows.Count; iSrc++)
                                {
                                    if (strServer == dtSyncDb.Rows[iDes]["Server"].ToString().ToLower() &&
                                        dtGlobalDatabase.Rows[iSrc]["name"].ToString().ToLower() == dtSyncDb.Rows[iDes]["Database"].ToString().ToLower())
                                    {
                                        dtGlobalDatabase.Rows.RemoveAt(iSrc);
                                        iSrc--;
                                        break;
                                    }
                                }
                            }
                        }
                        cbxDatabase.DataSource = dtGlobalDatabase;
                        cbxDatabase.DisplayMember = "name";
                        cbxDatabase.ValueMember = "name";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            //else
            //{
            //    MessageBox.Show("请在选择或添加同步组后再执行此操作!");
            //}
        }
        // 同步库点击事件
        private void dgvSyncDb_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            iSyncDbSelectedRowIndex = e.RowIndex;
        }
        // 添加同步库
        private void btnSyncDbAdd_Click(object sender, EventArgs e)
        {
            string strServer = cbxServer.Text;
            if (strServer == "")
            {
                MessageBox.Show("请选择服务器");
                cbxServer.Focus();
                return;
            }
            string strDatabase = cbxDatabase.Text;
            if (strDatabase == "")
            {
                MessageBox.Show("请选择数据库");
                cbxDatabase.Focus();
                return;
            }

            if (cbxServer.SelectedIndex > -1 && cbxDatabase.SelectedIndex > -1)
            {
                DataRow drSyncDb = lstSync[iSyncGpSelectedRowIndex].SyncDb.NewRow();

                drSyncDb["SdName"] = string.Format("[{0}].[{1}]", strServer, strDatabase);
                drSyncDb["IsMain"] = (lstSync[iSyncGpSelectedRowIndex].SyncDb.Rows.Count == 0);
                drSyncDb["Server"] = strServer;
                drSyncDb["Database"] = strDatabase;
                drSyncDb["IsSync"] = true;
                lstSync[iSyncGpSelectedRowIndex].SyncDb.Rows.Add(drSyncDb);
                dtGlobalDatabase.Rows.RemoveAt(cbxDatabase.SelectedIndex);
                cbxDatabase.DataSource = dtGlobalDatabase;
                //保存到数据库
                dgvSyncDb.DataSource = lstSync[iSyncGpSelectedRowIndex].SyncDb;
                if (lstSync[iSyncGpSelectedRowIndex].SyncDb.Rows.Count == 1)
                {
                    //更新同步表
                    SqlHelper.FillSyncDbSyncTb(lstSync[iSyncGpSelectedRowIndex]);
                    dgvSyncTb.DataSource = lstSync[iSyncGpSelectedRowIndex].SyncTb;
                    if (lstSync[iSyncGpSelectedRowIndex].SyncTb.Rows.Count > 0) SyncTbSelectedRow(0);
                }
            }
        }
        // 删除同步库时事件
        private void dgvSyncDb_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            DialogResult result = MessageBox.Show("你确定要移除该行配置吗？", "", MessageBoxButtons.YesNo);
            if (result == DialogResult.No)
            {
                e.Cancel = true;
            }
        }
        // 删除同步库后事件
        private void dgvSyncDb_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            //更新同步表
            if (iSyncDbSelectedRowIndex == 0)
            {
                SqlHelper.FillSyncDbSyncTb(lstSync[iSyncGpSelectedRowIndex]);
                dgvSyncTb.DataSource = lstSync[iSyncGpSelectedRowIndex].SyncTb;
                SyncTbSelectedRow(-1);
            }
        }


        // 同步组添加事件
        private void dgvSyncGp_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            lstSync.Add(new SyncItem());
        }
        // 同步组删除事件
        private void dgvSyncGp_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            DialogResult result = MessageBox.Show("你确定要移除该行配置吗？", "", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                //移除同步组
                lstSync.RemoveAt(iSyncGpSelectedRowIndex);
                //设置选中事件
                SyncGpSelectedRow(0);
            }
            else
            {
                e.Cancel = true;
            }
        }
        // 同步组点击事件
        private void dgvSyncGp_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            SyncGpSelectedRow(e.RowIndex);
            cbxServer_SelectedIndexChanged(null, null);//刷新数据库
        }
        // 同步组选中行处理
        private void SyncGpSelectedRow(int iRowIndex)
        {
            iSyncGpSelectedRowIndex = iRowIndex;
            if (iRowIndex > -1 && iRowIndex < lstSync.Count)
            {
                dgvSyncDb.DataSource = lstSync[iRowIndex].SyncDb;
                dgvSyncTb.DataSource = lstSync[iRowIndex].SyncTb;

                if (lstSync[iRowIndex].SyncTb.Rows.Count > 0) SyncTbSelectedRow(0);

                llbSelectAll.Enabled = true;
                llbSelectRvs.Enabled = true;

                cbxServer.Enabled = true;
                cbxDatabase.Enabled = true;
                btnSyncDbAdd.Enabled = true;
            }
            else
            {   //清空显示
                SyncItem syncitem = new SyncItem();
                dgvSyncDb.DataSource = syncitem.SyncDb;
                dgvSyncTb.DataSource = syncitem.SyncTb;

                SyncTbSelectedRow(-1);//清空列

                llbSelectAll.Enabled = false;
                llbSelectRvs.Enabled = false;

                cbxServer.Enabled = false;//cbxServer.Text = "";
                cbxDatabase.Enabled = false;//cbxDatabase.Text = "";
                btnSyncDbAdd.Enabled = false;
            }
        }
        //配置出错处理(同步间隔数据类型)
        private void dgvSyncGp_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            if (dgvSyncGp.Columns[e.ColumnIndex].Name == "dgvSyncGp_txtSpaced")
            {
                MessageBox.Show("请输入有效的数字!");
                e.Cancel = true;
            }
        }

        // 全选
        private void llbSelectAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (iSyncGpSelectedRowIndex > -1 && iSyncGpSelectedRowIndex < lstSync.Count)
            {
                bool isSelectAll = true;
                DataTable dtSyncTb = lstSync[iSyncGpSelectedRowIndex].SyncTb;
                for (int i = 0; i < dtSyncTb.Rows.Count; i++)
                {
                    if (!Convert.ToBoolean(dtSyncTb.Rows[i]["IsSync"]))
                    {
                        isSelectAll = false; break;
                    }
                }

                for (int i = 0; i < dtSyncTb.Rows.Count; i++)
                {
                    dtSyncTb.Rows[i]["IsSync"] = !isSelectAll;
                }
            }
        }
        // 反选
        private void llbSelectRvs_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (iSyncGpSelectedRowIndex > -1)
            {
                DataTable dtSyncTb = lstSync[iSyncGpSelectedRowIndex].SyncTb;
                for (int i = 0; i < dtSyncTb.Rows.Count; i++)
                {
                    dtSyncTb.Rows[i]["IsSync"] = !Convert.ToBoolean(dtSyncTb.Rows[i]["IsSync"]);
                }
                dgvSyncTb.DataSource = dtSyncTb;
            }
        }


        // 同步表点击事件
        private void dgvSyncTb_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            SyncTbSelectedRow(e.RowIndex);
        }

        // 同步组选中行处理
        private void SyncTbSelectedRow(int iRowIndex)
        {
            iSyncTbSelectedRowIndex = iRowIndex;
            if (iRowIndex > -1 && iRowIndex < lstSync[iSyncGpSelectedRowIndex].SyncTb.Rows.Count)
            {
                if (lstSync[iSyncGpSelectedRowIndex].SyncTb.Rows.Count > 0)
                {
                    if (lstSync[iSyncGpSelectedRowIndex].SyncTb.Rows[iSyncTbSelectedRowIndex]["Column"] != null)
                    {
                        dgvColumn.DataSource = lstSync[iSyncGpSelectedRowIndex].SyncTb.Rows[iSyncTbSelectedRowIndex]["Column"];
                    }
                }
            }
            else
            {
                dgvColumn.DataSource = SyncItem.CreateColumnTable();
            }
        }

        #endregion

        #region 辅助方法

        // 转List到Table
        private void ListToTable(List<SyncItem> lstSync, DataTable dtSyncGp)
        {
            dtSyncGp.Rows.Clear();
            for (int i = 0; i < lstSync.Count; i++)
            {
                DataRow drGroup = dtSyncGp.NewRow();
                drGroup["SgName"] = lstSync[i].SgName;
                drGroup["Spaced"] = lstSync[i].Spaced;
                drGroup["IsSync"] = lstSync[i].IsSync;
                dtSyncGp.Rows.Add(drGroup);
            }
        }
        // 转Table到List
        private void TableToList(DataTable dtSyncGp, List<SyncItem> lstSync)
        {
            for (int i = 0; i < lstSync.Count; i++)
            {
                object objIsSync = dtSyncGp.Rows[i]["IsSync"];
                if (objIsSync != DBNull.Value && Convert.ToBoolean(objIsSync))
                {
                   lstSync[i].IsSync = true;
                }
                else
                {
                    lstSync[i].IsSync = false;
                }
                lstSync[i].SgName=dtSyncGp.Rows[i]["SgName"].ToString();
                try
                {
                    lstSync[i].Spaced = Convert.ToInt32(dtSyncGp.Rows[i]["Spaced"]);
                }
                catch
                {
                    lstSync[i].Spaced = 10;
                }
            }
        }

        #region 委托/事件

        private delegate void ConfigureMessageDelegate(string format, params object[] args);
        public void ConfigureMessageEvent(string format, params object[] args)
        {
            if (lblPrompt.InvokeRequired)
            {
                BeginInvoke(new ConfigureMessageDelegate(ConfigureMessageEvent), new object[] { format,args });
            }
            else
            {
                if (format != null)
                {
                    string strMsg = DateTime.Now.ToString("HH:mm:ss.fff") + " " + string.Format(format, args);
                    lblPrompt.Text = strMsg;
                    LogHelper.AddLog(strMsg);
                }
                else
                {
                    lblPrompt.Text = "";
                }
            }
        }

        // 界面 启用|禁用 委托
        private delegate void FromEnabledDelegate(bool isEnable);
        public void FromEnabledEvent(bool isEnable)
        {
            if (this.InvokeRequired)
            {
                BeginInvoke(new FromEnabledDelegate(FromEnabledEvent), new object[] { isEnable });
            }
            else
            {
                groupBox1.Enabled = isEnable;
            }
        }

        #endregion

        private void dgvSyncTb_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            for (int i = 0; i < dgvSyncTb.RowCount; i++)
            {
                DataTable dtColumn =lstSync[iSyncGpSelectedRowIndex].SyncTb.Rows[i]["Column"] as DataTable;// 当前表的列
                List<string> lstScPkeyColumn = SqlHelper.GetScPkeyUniqueColumn(dtColumn);
                if (lstScPkeyColumn.Count == 0)
                {
                    List<string> lstDeOnlyColumn = SqlHelper.GetDeOnlyUniqueColumn(dtColumn);
                    if (lstDeOnlyColumn.Count == 0)
                    {
                        // 灰色
                        dgvSyncTb.Rows[i].Cells[0].Style.ForeColor = Color.Gray;
                    }
                    // 斜体
                    dgvSyncTb.Rows[i].Cells[0].Style.Font = new Font(dgvSyncTb.Font, FontStyle.Italic);// FontStyle.Bold | FontStyle.Italic
                }
            }
        }
       #endregion
    }
}